<?php
include_once('common.inc.php');
include_once(__ROOT__.'model/permission.class.php');

$act = get_param('action');
$permissionModel = new PermissionModel;

switch( $act ):

case 'add':
	if( get_param('submit') && get_param('taskids') ){
		$tasks = get_param('taskids');
		$tasks = trim($tasks,',');
		$arr_task = explode(',',$tasks);
		$data = array();
		$data['user_group'] = get_param('user_group');
		$permissionModel->del_permission($data);
		foreach( $arr_task as $v ){
			$data['task'] = $v;
			$rs = $permissionModel->add_permission($data);	
		}
		if( $rs ){
			echo '<p>Success!</p>';
		}else{
			echo '<p>'.$permissionModel->get_error().'</p>';
		}
	}
	include_once(__ROOT__.'model/userGroup.class.php');
	$group = new UserGroupModel;
	$groups = $group->get_all_group();
	$strOption = "";
	$strHidden = "";
	foreach( $groups as $v ){
		$strOption .= '<option value="'.$v['id'].'">'.$v['name'].'</option>';
		$group_tasks = $permissionModel->get_group_task_ids($v['id']);
		$strHidden .= '<input id="permission_'.$v['id'].'" type="hidden" value="'.implode(',',$group_tasks).'" />';
	}
	include_once(__ROOT__.'model/task.class.php');
	$task = new taskModel;
	$tasks = $task->get_all_task();
	$curt_group = get_param('user_group') ? get_param('user_group') : $groups[0]['id'];
	$group_tasks = $permissionModel->get_group_task_ids($curt_group);
	$strCheckbox = $strTaskids = "";
	foreach( $tasks as $v ){
		if( in_array($v['id'],$group_tasks) ){
			$checked = ' checked="true"';
			$strTaskids .= $v['id'].',';
		}else{
			$checked = "";
		}
		$strCheckbox .= '<input id="task_'.$v['id'].'" type="checkbox"'.$checked.' name="task" value="'.$v['id'].'" />'.$v['name']."\t";
	}
	include('head.php');
	echo '
		<fieldset>
			<legend>授权</legend>
			<form action="permission.php?action=add" method="post">
				<p>
					<label for="user_group">用户组：</label>
					<select id="sel_groups" name="user_group">'.$strOption.'</select>
					<input name="taskids" type="hidden" value="'.$strTaskids.'" />'.$strHidden.'
				</p>	
				<p>'.$strCheckbox.'</p>
				<p>
					<input type="submit" value="Submit" name="submit"  />
				</p>
			</form>
		</fieldset>
	';
break;

endswitch;
